package com.jlz.service.email;

import java.io.StringWriter;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import com.julewa.Configuration;
import com.julewa.freemarker.FreemarkerBuilder;
import com.julewa.freemarker.FreemarkerManager;

@Component
public class EmailService {
	private @Autowired Configuration conf = null;
	private @Autowired BinaryResources resources = null;
	
	private JavaMailSenderImpl sender = null;
	private FreemarkerManager freemarker = null; 
	private String email_from = null;
	public EmailService(){}
	
	@SuppressWarnings("unused")
	@PostConstruct
	private void init(){
		freemarker = new FreemarkerManager(EmailService.class, "ftl");
		//
		sender = new JavaMailSenderImpl();
		sender.setHost(conf.getProperty("email.sender.host", "localhost"));
		sender.setPort(Integer.parseInt(conf.getProperty("email.sender.port", "25")));
		sender.setUsername(conf.getProperty("email.sender.username", "hopenful"));
		sender.setPassword(conf.getProperty("email.sender.password", "hopenful"));
		if("true".equals(conf.getProperty("email.sender.auth", "false"))){
			Properties prop = new Properties(); 
			prop.setProperty("mail.smtp.auth", "true"); 
			sender.setJavaMailProperties(prop);
		}
		//
		email_from = conf.getProperty("email.sender.from", "julezu.com@no-reply.julezu.com");
	}
	

	//
	public boolean sendRegisterNotice(String to, String username, String activeurl){
		//create mail text
		FreemarkerBuilder builder = freemarker.load("registerNotice");
		builder.put("username",  username);
		builder.put("activeurl", activeurl);
		try {
			MimeMessage msg = sender.createMimeMessage();
			sender.send(new FreemarkerEmailBuilder(builder, resources, msg).build(email_from, to));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean sendResetPassword(String to, String username, String newpassword){
		StringWriter writer = new StringWriter();
		FreemarkerBuilder builder = freemarker.load("resetPassword");
		builder.put("username", username);
		builder.put("emailto", to);
		builder.put("password", newpassword);
		builder.build(writer);
		//
		try {
			MimeMessage msg = sender.createMimeMessage();
			sender.send(new FreemarkerEmailBuilder(builder, resources, msg).build(email_from, to));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
}
